import { useEffect, useRef } from 'react'

const useUpdateEffect = <T>(cb: () => void, deps: T[]): void => {
  const mountedRef = useRef(false)

  useEffect(() => {
    return () => {
      // 组件卸载的时候重置状态，防止组件卸载的时候执行回调函数
      mountedRef.current = false
    }
  }, [])

  useEffect(() => {
    // 跳过初次渲染时执行cb
    if (!mountedRef.current) {
      mountedRef.current = true
    } else {
      return cb()
    }
  }, deps)
}

export default useUpdateEffect